package com.jacobson.huobi.services

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Message
import androidx.annotation.RequiresApi
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.R
import com.jacobson.huobi.websocket.WebsocketManager


/**
 * Websocket后台服务
 */
class WebsocketService : Service() {
    private val logger = LoggerFactory.getLogger()
    private var handler: WebsocketService.MyHandler? = null
    override fun onBind(intent: Intent?): IBinder? {
        logger.i("WebsocketService is onBind")
        throw UnsupportedOperationException("Not yet implemented")
        return null
    }

    override fun onCreate() {
        super.onCreate()
        handler = MyHandler()
    }
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        logger.d("WebsocketService is onStartCommand")
        val type = intent?.getIntExtra("type", 1)

        if (type == 1) {
            createNotificationChannel()
        } else {
            createErrorNotification()
        }
        object : Thread() {
            override fun run() {
                super.run()
                try {
                    sleep(5000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                handler?.sendEmptyMessage(startId)
            }
        }.start()
        WebsocketManager.startWebsocketConnectThread()
        return super.onStartCommand(intent, flags, startId)
    }
    private fun createErrorNotification() {
        val notification = Notification.Builder(this).build()
        startForeground(0, notification)
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val mNotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            // 通知渠道的id
            val id = "my_channel_01"
            // 用户可以看到的通知渠道的名字.
            val name: CharSequence = getString(R.string.channel_name)
            //         用户可以看到的通知渠道的描述
            val description = getString(R.string.channel_description)
            val importance = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(id, name, importance)
            //         配置通知渠道的属性
            mChannel.description = description
            //         设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true)
            mChannel.lightColor = Color.RED
            //         设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true)
            mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            //         最后在notificationmanager中创建该通知渠道 //
            mNotificationManager.createNotificationChannel(mChannel)
            // 为该通知设置一个id
            val notifyID = 1
            // 通知渠道的id
            val CHANNEL_ID = "my_channel_01"
            // Create a notification and set the notification channel.
            val notification: Notification = Notification.Builder(this)
                .setContentTitle("New Message").setContentText("You've received new messages.")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setChannelId(CHANNEL_ID)
                .build()
            startForeground(1, notification)
        }
    }

    private inner class MyHandler : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            stopSelf(msg.what)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }
}